package com.mail.transfer.email.schedule;

import com.mail.transfer.email.PopInfo;
import com.mail.transfer.email.RecvMailsThread;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import java.util.Properties;

/**
 * @author xiaocg
 * 定时拉取邮件
 */
public class MailPullScheduledTask implements Runnable{

    private Store store;
    private String host;

    public MailPullScheduledTask(PopInfo info,String host){
        try {
            this.host = host;
            Properties p = new Properties();
            // SSL安全连接参数
            p.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            p.setProperty("mail.pop3.socketFactory.fallback", "true");
            Session session = Session.getDefaultInstance(p, null);
            store = session.getStore("pop3");
            store.connect(info.getHost(), info.getUsername(), info.getPassword());
        }catch (Exception e){

        }
    }

    @Override
    public void run() {
        try {
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] messages = folder.getMessages();
            System.out.println("邮件数量:　" + messages.length);
            new RecvMailsThread(messages,host).start();
        }catch (Exception e){

        }
    }

}
